<template>
  <el-dialog
    v-el-drag-dialog
    :title="type === 'add' ? '新增车辆配置' : '编辑车辆配置'"
    :visible.sync="visible"
    width="700px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="80px">
      <el-form-item label="车辆" prop="truckCode">
        <el-select v-model="temp.truckCode" placeholder="请选择" clearable>
          <el-option
            v-for="item in vehicleList"
            :key="item.truckId"
            :label="item.truckCode"
            :value="item.truckCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="司机" prop="driverUserIds">
        <el-select v-model="temp.driverUserIds" multiple placeholder="请选择" clearable>
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in driverList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="押运员" prop="escortUserIds">
        <el-select v-model="temp.escortUserIds" multiple placeholder="请选择" clearable>
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in driverList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="remark" class="block">
        <label slot="label">备注</label>
        <el-input v-model="temp.remark" type="textarea" :rows="3" maxlength="250" show-word-limit />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { vehicleSettingAdd } from '@/api'
  import { mapGetters } from 'vuex'

  export default {
    name: 'add-setting',
    props: {
      vehicleList: {
        type: Array,
        required: true
      },
      driverList: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        visible: false,
        type: 'add',
        temp: {
          truckCode: '',
          driverUserIds: [],
          escortUserIds: [],
          remark: ''
        },
        oldTruckCode: '',
        oldTruckId: 0,
        rules: {
          truckCode: [{ required: true, message: '请选择车辆', trigger: 'change' }],
          driverUserIds: [{ required: true, message: '请选择司机', trigger: 'blur' }],
          escortUserIds: [{ required: true, message: '请选择押运员', trigger: 'blur' }]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    watch: {
      'temp.driverUserIds': function(val, oldval) {
        if (!val || !oldval) return
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.temp.driverUserIds = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.temp.driverUserIds.splice(val.indexOf(0), 1)
        }
        if (this.temp.driverUserIds.length === 0) this.temp.driverUserIds = [0] // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'temp.escortUserIds': function(val, oldval) {
        if (!val || !oldval) return
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) { // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.temp.escortUserIds = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) { // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.temp.escortUserIds.splice(val.indexOf(0), 1)
        }
        if (this.temp.escortUserIds.length === 0) this.temp.escortUserIds = [0] // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      }
    },
    methods: {
      open(temp) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(temp)
            const driverNamesArr = temp.driverNames.split(',')
            const escortNamesArr = temp.escortNames.split(',')
            this.temp.driverUserIds = driverNamesArr.map(item => {
              const match = this.driverList.find(it => it.userName === item)
              if (match) return match.userId
              return null
            })
            this.temp.escortUserIds = escortNamesArr.map(item => {
              const match = this.driverList.find(it => it.userName === item)
              if (match) return match.userId
              return null
            })
            this.oldTruckCode = temp.truckCode
            this.oldTruckId = temp.truckId
            this.type = 'edit'
          }
        })
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const params = {
            truckCode: this.temp.truckCode,
            driverUserIds: this.temp.driverUserIds,
            escortUserIds: this.temp.escortUserIds,
            remark: this.temp.remark
          }
          let driverUserNames, escortUserNames
          if (this.temp.driverUserIds[0] !== 0) { // 不是选的全部
            driverUserNames = this.temp.driverUserIds.map(item => {
              const match = this.driverList.find(it => it.userId === item)
              return match.userName
            })
            params.driverUserIds = this.temp.driverUserIds.join(',')
          } else {
            driverUserNames = this.driverList.map(item => item.userName)
            params.driverUserIds = this.driverList.map(item => item.userId).join(',')
          }
          if (this.temp.escortUserIds[0] !== 0) { // 不是选的全部
            escortUserNames = this.temp.escortUserIds.map(item => {
              const match = this.driverList.find(it => it.userId === item)
              return match.userName
            })
            params.escortUserIds = this.temp.escortUserIds.join(',')
          } else {
            escortUserNames = this.driverList.map(item => item.userName)
            params.escortUserIds = this.driverList.map(item => item.userId).join(',')
          }
          params.driverUserNames = driverUserNames.join(',')
          params.escortUserNames = escortUserNames.join(',')
          params.oldTruckCode = this.oldTruckCode
          params.oldTruckId = this.oldTruckId
          if (this.type === 'add') {
            this.add(params)
          } else {
            this.edit(params)
          }
        })
      },
      async add(params) {
        await vehicleSettingAdd({ paramInfo: params })
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      },
      async edit(params) {
        console.log(params, 222)
        await vehicleSettingAdd({ paramInfo: params })
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.type = 'add'
        this.temp = {
          truckCode: '',
          driverUserIds: [],
          escortUserIds: [],
          remark: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 20px;
  .title-icon {
    display: inline-block;
    width: 4px;
    height: 18px;
    margin-right: 6px;
    background: $themeColor;
  }
  span {
    font-weight: 700;
    color: $themeColor;
  }
}
</style>
